import axios from 'axios'
import { serialize } from '@/utils/index'
import { Message } from 'element-ui'
import errorCode from '@/const/errorCode'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 60000 // request timeout
})

const excludeApis = ['/data-dict/api', '/select-service/api'] // 外部api地址

// 请求拦截
service.interceptors.request.use(
  config => {
    const isToken = (config.headers || {}).isToken === false
    if (store.getters.token && !isToken) {
      config.headers['token'] = getToken()
      config.headers['Authorization'] = `Bearer ${getToken()}`
    }
    // headers中配置serialize为true开启序列化
    if (config.methods === 'post' && config.headers.serialize) {
      config.data = serialize(config.data)
      delete config.data.serialize
    }

    excludeApis.forEach(path => {
      if (config.url.indexOf(path) === 0) {
        config.baseURL = ''
      }
    })

    // if (config.url.indexOf('/data-dict/api') === 0) {
    //   config.baseURL = ''
    // }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    Message.error('请求超时！请重试！')
    return Promise.reject(error)
  }
)

const idReg = /^([a-z0-9A-Z]+-)+[a-z0-9A-Z]+$/
// 返回拦截
service.interceptors.response.use(response => {
  const res = response.data
  const message = res.msg || errorCode[status] || errorCode['default']

  if (res.success === 0) {
    // console.log(response, '===========')
    // 定时任务不报错
    if (!response.config.hiddenError) {
      Message({
        message: message,
        type: 'error',
        showClose: true
      })
    }
    // 字节接口获取虚拟号
    if (response.config.url.includes('virtual-number')) {
      return Promise.reject(res)
    }
    return Promise.reject(message)
  }

  // 工单相关额外提示信息
  if (res.code === '10001' || res.code === 10001) {
    const msg = res.msg
    const msgData = res.data
    let tipMsg = ''
    typeof msg === 'string' && !idReg.test(msg) && (tipMsg += msg)
    typeof msgData === 'string' && !idReg.test(msgData) && (tipMsg += msgData)
    tipMsg && (Message({
      message: tipMsg,
      type: 'warning',
      showClose: true
    }))
  }

  if (response.config.responseType === 'blob' || response.config.responseType === 'arraybuffer') {
    return response
  }

  return res
}, error => {
  const res = error.response.data
  const status = Number(error.response.status) || 200
  const message = res.msg || errorCode[status] || errorCode['default']
  if (status === 401 || res.code === 401 || res.code === '401') {
    if (!window.location.href.includes('/login')) {
      store.dispatch('user/resetToken').then(() => {
        Message({
          message: message === '' || message === 'error' ? '身份验证错误，请重新登录' : message,
          type: 'error',
          duration: 1500,
          onClose: function() {
            window.location.href = '/'
          }
        })
      })
    }
    return Promise.reject(error)
  }

  if (status !== 200) {
    if (!window.location.href.includes('/login')) {
      if (!error.config.hiddenError) {
        Message({
          message: message,
          type: 'error',
          showClose: true
        })
      }
    }
    return Promise.reject(error)
  }

  return Promise.reject(error)
})

export default service
